﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data.Entity.Infrastructure;
using BPM.Entity;
using BPM.Common;
using Webdiyer.WebControls.Mvc;
using System.Data.Entity;
using System.Transactions;

namespace BPM.Service
{
	public class UserService : ServiceBase<User>
	{
		protected override IQueryable<User> PrepareToQuery(DbSet<User> set)
		{
			return base.PrepareToQuery(set)
				.Include(u => u.RoleList);
		}

		protected override void EnableLazyLoadingCore(User entity)
		{
			base.EnableLazyLoadingCore(entity);

			EnableChildrenLazyLoading(entity.RoleList);
		}

		/// <summary>
		/// 添加一个新用户
		/// </summary>
		/// <param name="user"></param>
		/// <returns></returns>
		public Result AddUser(string userName, string realName, string pwd, out User newUser)
		{
			newUser = this.GetByUserName(userName);

			if (newUser != null) return "用户名存在";

			Barcode barcode = null;
			var res = new BarcodeService().New(SysBarcodeCategories.User, out barcode);
			if (!res) return res;

			User user = new User();
			user.IsValid = false;
			user.Password = pwd;
			user.RealName = realName;
			user.UserName = userName;
			user.Barcode = barcode;
			user.BarcodeId = barcode.Id;

			newUser = user;
			return this.Create(user).ReplaceMessage("注册成功", "注册失败");
		}

		public override Result Delete(int id)
		{
			using (var t = new TransactionScope())
			{
				var result = this.Delete(id, u =>
				{
					//var user = this.GetById(u.Id);

					//var roleSvc = new RoleService();
					//foreach (var role in user.RoleList)
					//{
					//    var res = roleSvc.Delete(role.Id);
					//    if (!res) return res;
					//}
					return true;
				}, u =>
				{
					return new BarcodeService().Delete(u.BarcodeId);
				});

				t.Complete();

				return result;
			}
		}

		///// <summary>
		///// 删除一个用户
		///// </summary>
		///// <param name="userId"></param>
		///// <returns></returns>
		//public Result DeleteUser(int userId)
		//{
		//    User user = this.GetById(userId);

		//    var db = this.NewContext();

		//    if (user != null)
		//    {
		//        var set = db.Set<User>();
		//        set.Attach(user);
		//        set.Remove(user);

		//        return db.Save().ReplaceMessage("删除成功", "删除失败");
		//    }
		//    else
		//    {
		//        return "用户不存在";
		//    }
		//}

		public Result ResetRoles(int userId, string roles, User curUser)
		{
			if (!curUser.HasRole(SysRoles.Admin) &&
				!curUser.HasRole(SysRoles.Manager))
			{
				return "没有权限执行此操作。";
			}

			var context = this.NewContext();
			var user = context.Set<User>()
				.Include(u => u.RoleList)
				.FirstOrDefault(u => u.Id == userId);
			if (user == null) return "没有找到指定的用户。";

			var rolesId = roles.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
				.Select(str => Convert.ToInt32(str)).ToArray();

			user.RoleList.Clear();
			foreach (var roleId in rolesId)
			{
				//if (!user.HasRole(roleId))
				{
					var role = context.Set<Role>().FirstOrDefault(r => r.Id == roleId);
					if (role == null) return "没有找到指定的角色。";
					user.RoleList.Add(role);
				}
			}

			var res = context.Save();
			return res;
		}

		/// <summary>
		/// 允许未验证的用户进入系统
		/// </summary>
		/// <param name="userId"></param>
		/// <returns></returns>
		public Result AllowNotValidUser(int userId)
		{
			var user = this.GetById(userId);
			if (user == null) return "用户不存在";

			user.IsValid = true;
			return this.Update(user);
		}

		#region Query

		/// <summary>
		/// 用户登录
		/// </summary>
		/// <param name="user"></param>
		/// <returns></returns>
		public Result Logon(string userName, string password, out User currentUser)
		{
			currentUser = this.Query()
				.FirstOrDefault(u => u.UserName == userName && u.Password == password);

			this.EnableLazyLoading(currentUser);

			return new Result(currentUser != null)
				.ReplaceMessage("登录成功", "登录失败");
		}

		/// <summary>
		/// 判断给定用户名是否已经存在.
		/// Result.Success为false,说明不存在.反之true为存在.
		/// </summary>
		/// <param name="userName"></param>
		/// <returns></returns>
		public bool IsUserNameExist(string userName)
		{
			return this.Query().Any(u => u.UserName == userName);
		}

		public User GetByUserName(string userName)
		{
			return this.Query().FirstOrDefault(u => u.UserName == userName);
		}

		/// <summary>
		/// 得到未验证的用户(刚注册) [分页]
		/// </summary>
		/// <param name="pageIndex"></param>
		/// <param name="pageSize"></param>
		/// <returns></returns>
		public PagedList<User> GetNotValidUserList(int pageIndex, int pageSize)
		{
			PagedList<User> users = this.Query()
				.Where(u => u.IsValid == false)
				.OrderBy(u => u.RealName)
				.ToPagedList(pageIndex, pageSize);
			return users;
		}

		/// <summary>
		/// 获取全部用户 [分页]
		/// </summary>
		/// <param name="pageIndex"></param>
		/// <param name="pageSize"></param>
		/// <returns></returns>
		public PagedList<User> GetAllUser_WithRoles(int pageIndex, int pageSize)
		{
			PagedList<User> users = this.Query()
				.Include(u => u.RoleList)
				.OrderBy(u => u.RealName)
				.ToPagedList(pageIndex, pageSize);
			return users;
		}

		#endregion
	}
}